import { useUserStore } from '@/store/user'
import { GameObject } from '@/assets/scripts/GameObject'
import { Player } from '@/assets/scripts/Player'
export class SingleMap extends GameObject {
    constructor(ctx, difficulty = 'first') {
        super()
        this.ctx = ctx
        this.difficulty = difficulty
        this.width = this.ctx.canvas.width
        this.height = this.ctx.canvas.height

        // 玩家列表
        this.players = []

        // 游戏状态
        this.gameOver = false
        this.gameWon = false
        this.gameEvents = {
            onGameOver: null, // 游戏结束事件
            onPlayerDeath: null, // 玩家死亡事件
        }

        // 游戏显示设置
        this.aspectRatio = { width: 16, height: 9 }

        // 玩家参数比例
        this.sizeConfig = {
            playerRadius: 0.05, // 玩家半径占画面高度的比例
            playerSpeed: 0.15, // 玩家速度占画面高度的比例
        }

        this.resize()

        this.initPlayers()
    }

    // 设置游戏事件回调函数
    setEventCallback(eventName, callback) {
        // 修改后：使用安全的属性检查方式
        if (Object.prototype.hasOwnProperty.call(this.gameEvents, eventName)) {
            this.gameEvents[eventName] = callback
        }
    }

    // 玩家死亡事件处理
    playerDeath(player) {
        // 检查是否是主玩家死亡
        if (player.info.role === 'me') {
            this.gameOver = true
            this.gameWon = false

            // 调用游戏结束回调
            if (typeof this.gameEvents.onGameOver === 'function') {
                this.gameEvents.onGameOver(false)
            }
        } else if (player.info.role === 'AI') {
            // 如果是AI死亡，检查是否所有AI都死亡
            let allAiDead = true
            for (let i = 0; i < this.players.length; i++) {
                if (this.players[i].info.role === 'AI' && !this.players[i].is_dead) {
                    allAiDead = false
                    break
                }
            }

            // 如果所有AI都死亡，玩家胜利
            if (allAiDead) {
                this.gameOver = true
                this.gameWon = true

                // 调用游戏结束回调
                if (typeof this.gameEvents.onGameOver === 'function') {
                    this.gameEvents.onGameOver(true)
                }
            }
        }

        // 调用玩家死亡回调
        if (typeof this.gameEvents.onPlayerDeath === 'function') {
            this.gameEvents.onPlayerDeath(player)
        }
    }

    // 根据难度级别返回AI玩家数量
    getAiCountByDifficulty(difficulty) {
        switch (difficulty) {
            case 'first':
                return 3
            case 'second':
                return 5
            case 'third':
                return 4
            case 'fourth':
                return 7
            default:
                return 3
        }
    }

    // 生成一个随机颜色给AI玩家
    get_random_color() {
        let colors = ['red', 'blue', 'green', 'yellow', 'orange', 'purple', 'pink', 'brown', 'gray']
        return colors[Math.floor(Math.random() * colors.length)]
    }

    // 生成随机位置，确保不与其他玩家重叠
    getRandomPosition() {
        const margin = this.height * this.sizeConfig.playerRadius * 3 // 边缘安全距离
        const maxAttempts = 10 // 最大尝试次数

        for (let i = 0; i < maxAttempts; i++) {
            // 生成随机位置
            const x = margin + Math.random() * (this.width - 2 * margin)
            const y = margin + Math.random() * (this.height - 2 * margin)

            // 检查是否与其他玩家重叠
            let overlapping = false
            for (const player of this.players) {
                const dist = Math.sqrt(
                    Math.pow(player.info.x - x, 2) + Math.pow(player.info.y - y, 2)
                )
                if (dist < this.height * this.sizeConfig.playerRadius * 4) {
                    overlapping = true
                    break
                }
            }

            // 如果没有重叠，返回此位置
            if (!overlapping) {
                return { x, y }
            }
        }

        // 如果找不到合适位置，返回随机位置
        return {
            x: margin + Math.random() * (this.width - 2 * margin),
            y: margin + Math.random() * (this.height - 2 * margin),
        }
    }

    // 初始化玩家
    initPlayers() {
        const userStore = useUserStore()

        // 获取玩家位置（中心位置）
        const playerPos = {
            x: this.width / 2,
            y: this.height / 2,
        }

        // 添加自己
        this.players.push(
            new Player(this, {
                x: playerPos.x,
                y: playerPos.y,
                radius: this.height * this.sizeConfig.playerRadius,
                color: 'white',
                speed: this.height * this.sizeConfig.playerSpeed,
                hp: 100,
                role: 'me',
                photo: userStore.photo,
                username: userStore.username,
                userId: userStore.id,
            })
        )

        // 添加AI玩家
        const aiCount = this.getAiCountByDifficulty(this.difficulty)
        for (let i = 0; i < aiCount; i++) {
            // 获取随机位置，确保不会与其他玩家重叠
            const randomPos = this.getRandomPosition()

            this.players.push(
                new Player(this, {
                    x: randomPos.x,
                    y: randomPos.y,
                    radius: this.height * this.sizeConfig.playerRadius,
                    color: this.get_random_color(),
                    speed: this.height * this.sizeConfig.playerSpeed,
                    hp: 100,
                    role: 'AI',
                    photo: '',
                    username: 'AI ' + i,
                    userId: i,
                })
            )
        }
    }

    // 调整窗口大小执行
    resize() {
        const canvas = this.ctx.canvas
        const oldWidth = this.width || 1
        const oldHeight = this.height || 1

        // 获取父容器尺寸
        const parent = canvas.parentElement
        const parentWidth = parent.clientWidth
        const parentHeight = parent.clientHeight

        // 直接使用父容器尺寸，不再强制16:9比例
        this.width = canvas.width = parentWidth
        this.height = canvas.height = parentHeight

        // 只有在玩家列表已初始化后才更新玩家属性
        if (this.players && this.players.length > 0) {
            // 计算缩放比例
            const widthRatio = this.width / oldWidth
            const heightRatio = this.height / oldHeight

            // 更新玩家位置和属性
            for (let player of this.players) {
                if (!player || !player.info) continue
                
                player.info.x *= widthRatio
                player.info.y *= heightRatio

                player.info.radius = this.height * this.sizeConfig.playerRadius
                // resize时也要调整满血时的半径，用于后面根据玩家血量更新玩家半径
                player.initialRadius = player.info.radius
                player.info.speed = this.height * this.sizeConfig.playerSpeed

                player.width = this.width
                player.height = this.height
            }

            // 更新其他游戏对象，避免递归调用自身
            const gameObjects = GameObject.getObjects()
            for (let obj of gameObjects) {
                // 避免处理自身和已处理过的玩家对象
                if (obj === this || obj instanceof Player) continue
                
                // 确保对象有resize方法
                if (obj && typeof obj.resize === 'function') {
                    // 传递缩放比例但不传递this引用，避免可能的循环
                    try {
                        // 使用try-catch防止resize方法可能导致的错误
                        obj.resize(widthRatio, heightRatio)
                    } catch (error) {
                        console.warn("更新对象尺寸时出错:", error)
                    }
                }
            }
        }

        // 重新渲染
        this.render()
    }

    // 将玩家从玩家列表中移除
    removePlayer(player) {
        const index = this.players.indexOf(player)
        if (index !== -1) {
            this.players.splice(index, 1)
        }
    }

    start() {}

    update() {
        // 如果游戏已结束，只渲染不更新
        if (this.gameOver) {
            this.render()
            return
        }

        this.render()
    }

    render() {
        // 创建渐变背景
        this.ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
        this.ctx.fillRect(0, 0, this.width, this.height)

        // 如果游戏结束，显示游戏结果
        if (this.gameOver) {
            this.ctx.save()
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'
            this.ctx.fillRect(0, 0, this.width, this.height)

            this.ctx.font = '40px Arial'
            this.ctx.textAlign = 'center'
            this.ctx.textBaseline = 'middle'

            if (this.gameWon) {
                this.ctx.fillStyle = '#00ff88'
                this.ctx.fillText('胜利！', this.width / 2, this.height / 2 - 40)
                this.ctx.font = '24px Arial'
                this.ctx.fillText('你已经击败了所有敌人', this.width / 2, this.height / 2 + 20)
            } else {
                this.ctx.fillStyle = '#ff4444'
                this.ctx.fillText('失败！', this.width / 2, this.height / 2 - 40)
                this.ctx.font = '24px Arial'
                this.ctx.fillText('你被敌人击败了', this.width / 2, this.height / 2 + 20)
            }

            this.ctx.restore()
        }
    }
}
